<?php
namespace gzapi\inspect\controller;

use cmf\controller\PublicController;
use think\Validate;
use gzapi\common\business\InspectCompany;
use gzapi\common\model\GzHiseServiceInspectionModel;
use think\Db;
use gzapi\debug\controller\CompanyController as Debug;
use think\Log;
class CompanyController extends PublicController
{
    //方法验证参数
    protected $auth = '*';
    protected $install_status_new = [
        0 => '派工中',
        1 => '派工完成',
        2 => '提交之后',
        3 => '验证中',
        4 => '验证完成',
        5 => '检验完成',
    ];
   public function initialize(){
   }
    //进入巡检列表
    public function inspectList()
    {
     if($this->request->isPost()){
         $userData=$this->user;
         $azd_id=input('post.azd_id');
        if(isset($userData['et_azd_id'])){

            if($this->user['post']==1){
        //服务商
        $res=Db::table('cmf_gz_hise_service_inspection')->where([
            'xj_dw'=>$userData['server_code'],
            'xj_azdbh'=>$azd_id
            ])->select();
          //  dump(Db::table('cmf_gz_hise_service_inspection')->getLastsql());die;
            }else{
                $res=Db::table('cmf_gz_hise_service_inspection')->where([
                    'xj_azdbh'=>$azd_id,
                    'xj_xjr'=>$userData['engineer_code']
                    ])->select();
            }
        }else{
            //分公司
            $res=InspectCompany::getInspectData($azd_id,$userData);
        }
        if($res){
            $res=$res->toArray();
            foreach($res as $k=>$v){
                if($v['xj_is_wp']=='1'){
                    $res[$k]['xj_dw']=getazsName($v['xj_dw']);
                    $res[$k]['xj_xjr']=getazdName($v['xj_xjr']);
                }else{
                    $res[$k]['xj_dw']=getfgsName($v['xj_dw']);
                    $res[$k]['xj_xjr']=getgcsName($v['xj_fwgcs']);
                }
             }
        }
         $this->success('请求成功',$res);
        }
    }
    //查询服务商老板   ---后面补
    public function getdwdata(){
        $azd_id=input('post.azd_id');
        $keyword=input('post.keyword');
        $where=[];
        if($keyword!=""){
          $where['server_name']=['like',"%".$keyword."%"];
        }
        // 分公司code
        $userData=$this->user;
        $companyCode= Db::table('cmf_gz_hise_service_project')->where('azd_id',$azd_id)->value('fwfgs');
        $azdData=Db::table('cmf_rl_et_azs')->where('dept_name',$companyCode)->where($where)->where('server_proper',6)->where('active_flag',1)->select();
        // foreach($azsCode as $k=>$v){
        //    $res=Db::table('cmf_rl_et_azd')->where([
        //         'server_code'=>$v['server_code'],
        //    ])->field('engineer_code,engineer_name')->select();
        //  if(!empty($res)){
        //     $res=$res->toArray();
        //     foreach($res as $kr=>$vr){
        //         $azdData[]=$vr;
        //     }gi
        //  }
        // }
        //$res=Db::table('cmf_rl_et_azd')->where('dept_name',$userData['code'])->where('server_proper',6)->select();
        $this->success('操作成功',$azdData);
    }
   //查询服务商员工

    public function search_fwyg(){
         $userData=$this->user;
         $keyword=input('post.keyword');
         $where=[];
         if($keyword!=""){
           $where['engineer_name']=['like',"%".$keyword."%"];
         }
         $res=Db::table('cmf_rl_et_azd')->where('server_code',$userData['server_code'])->where($where)->where('post',2)->select();
         $this->success('查询成功',$res);
    }
    //老板接受派工   server_code---服务商员工编码
    public function save_fwyg($server_code,$xj_id){
      //  $server_code=input('server_code');
        //$xj_id=input('xj_id');
        $res=GzHiseServiceInspectionModel::where('xj_id',$xj_id)->setField([
            'xj_xjr'=> $server_code
       ]);
       if($res){
          $this->success('派工成功');
       }
       $this->success('派工失败');
    }
    //服务商员工接受派工  server_code---服务商员工编码
    public function save_fwjs($server_code,$xj_id){
        $res=GzHiseServiceInspectionModel::where('xj_id',$xj_id)->setField([
            'xj_xjr'=> $server_code,
            'xj_xjzt'=>1
       ]);
       if($res){
          $this->success('接受成功');
       }
       $this->success('接受失败');
    }
    //服务商老板驳回
    public function inspect_bh($xj_id){
       //$xj_id=input('xj_id');
       $res=GzHiseServiceInspectionModel::where('xj_id',$xj_id)->setField([
            'xj_dw'=>''
       ]);
       if($res){
            $this->success('驳回成功');
       }
       $this->success('驳回失败');
    }
    //服务人员驳回派工
    public function inspect_ygbh($xj_id){
       // $xj_id=input('xj_id');
        $res=GzHiseServiceInspectionModel::where('xj_id',$xj_id)->setField([
            'xj_xjr'=>''
       ]);
       if($res){
              $this->success('驳回成功');
       }
       $this->error('驳回成功');
    }
    //服务商老板派工/服务商员工派工   ----服务老板驳回/服务员工驳回
    //1为老板派工 2为老板驳回  3为员工派工  4 为员工驳回
    public function common_peartion(){
        $userData=$this->user;
        $type=input('post.type');
        $xj_id=input('post.xj_id');
        //服务商员工编码
        $server_code=input('post.server_code');
        if($userData['post']==2){
             //员工
             if($type==3){
               //接受派工
               $this->save_fwjs($server_code,$xj_id);
             }elseif($type==4){
              //驳回
               $this->inspect_ygbh($xj_id);
             }
        }else{
            //老板
            if($type==1){
              //接受派工
              $this->save_fwyg($server_code,$xj_id);
            }elseif($type==2){
              //驳回
             $this->inspect_bh($xj_id);

            }
        }
    }
    //重新派工
    public function resetdw(){
        if($this->request->isPost()){
            $userData=$this->user;
            $data=input('post.');
            $res=Db::table('cmf_gz_hise_service_inspection')->where([
                'xj_id'=>$data['xj_id']
                ])->update([
                    'xj_dw'=>$data['server_code'],
                ]);
                if($res){
                       $this->success('操作成功',[]);
                }
                $this->error('操作失败',[]);
        //     $userData=$this->user;
        //     $data=input('post.');
        //     $validate=new Validate([
        //         ['xj_id','require','巡检单号必传'],
        //         ['xj_xjr','require','服务商编码必传'],
        //     ]);
        //     if(!$validate->check($data)){
        //     $this->error($validate->getError(),[]);
        //     }
        //     //查询服务商
        //   $phone= Db::table('cmf_rl_et_azd')->where('server_code',$data['xj_xjr'])->value('phone');
        //   if(!$phone){
        //        $this->error('该服务商暂无可用人员');
        //   }
        //    $res= Db::table('cmf_gz_hise_service_inspection')->whe re('xj_id',$data['xj_id'])->update(['xj_xjr'=>$phone]);
        //     //$res=InspectCompany::updateInspectData($userData,$data);
        //     if($res){
        //         $this->success('更改成功',[]);
        //     }else{
        //         $this->error('更改失败',[]);
        //     }
        }
    }
    //创建巡检
    public function inspectAdd()
    {
     if($this->request->isPost()){
         $userData=$this->user;
         $data=input('post.');
         $data['xj_azdbh']=input('post.azd_id');
         $validate=new Validate([
             ['xj_azdbh','require','工程单号未传'],
             ['xj_is_wp','require|in:0,1','请选择是否外派|选择外派参数错误'],
         ]);
       if(!$validate->check($data)){
           $this->error($validate->getError(),[]);
       }
       $prores=Db::table('cmf_gz_hise_service_project')->where('azd_id',input('post.azd_id'))->find();
       if($prores['bxq_upd_bs']==1){
            $this->error('竣工后不能创建巡检');
       }
       //if($data['xj_is_wp']==1 and !$data['xj_xjr']){
          // $this->error('请选择服务商');
      // }
         $debug=new Debug();
         $data['xj_inspectcode']=$debug->nonceStr();
         $res=InspectCompany::createInspection($userData,$data);

         
         Db::table('cmf_gz_hise_service_project')->where('azd_id',$data['xj_azdbh'])->update([
             'inspection'=>1
         ]);
         $this->success('添加完成',[]);
    //    if($res){
    //        $this->success('添加完成',[]);
    //    }
    //      $this->error('添加失败',[]);
     }
    }

    //查看巡检详细信息
    public function inspectInfo()
    {
        // 验证的规则
        $rule = [
            'azd_id' => 'require',
            'inspectId' => 'require',
        ];
        // 错误的消息
        $msg = [
            'azd_id.require' => '安装单编号不存在',
            'inspectId.require' => '巡检单编号',
        ];
        // 获取的数据
      $data = [
            'azd_id' => $this->request->post('azd_id'), // 获取安装单编号
            'inspectId' =>$this->request->post('inspectId'), // 获取巡检单编号
        ];
        // 直接传入验证规则
        $validate = Validate::make($rule)->message($msg);
        // 需要验证的数据
        $result = $validate->check($data);
        // 判断是否有验证错误
        if (!$result) {
            // 验证错误提示
            $this->error($validate->getError());
        }
        //节点
        $data['hise_service_project_id']=Db::table('cmf_gz_hise_service_project')->where('azd_id',$data['azd_id'])->value('hise_service_project_id');
        // 获取工程单信息
        $hise_service_projec_info = Db::table('cmf_gz_hise_service_project')->where('hise_service_project_id', $data['hise_service_project_id'])->field('gczt,jxs,type,strategic_partner_name,jxs_name,vip_type,chain_type')->find();
         
        if(!$hise_service_projec_info){
             $this->error('该工程状态缺少');
        }
        $data['strategic_partner_name']=$hise_service_projec_info['strategic_partner_name'];
        $data['jxs_name']=$hise_service_projec_info['jxs_name'];
        $data['vip_type']=$hise_service_projec_info['vip_type'];
        $data['chain_type']=$hise_service_projec_info['chain_type'];
	$inspect=Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$data['inspectId'])->find();
        // 安装单状态格式化
        $data['status_text'] = $this->install_status_new[$inspect['xj_xjzt']];
        // 获取所有节点类型
        //$node_where=['type'=>1];
          if($this->request->post('zl')==1){
            $node_where=['type'=>3];  
        }else{
            $node_where=['type'=>1];
        }
        $list = Db::table('cmf_gz_node')
            // ->where('type_id', 'in', $hise_service_projec_info['type'])
            ->where($node_where)
            ->order('type_id ASC')
            ->select()
            ->toArray();

        if(input('post.yz')==2){
            $list=Db::table('cmf_gz_hise_service_inspection_step')
            ->alias('inspect')
            ->join('cmf_gz_node node', 'inspect.jd_azjd=node.node_id','left')
            ->where('inspect.jd_yz',1)
            ->where($node_where)
            ->where('inspect.jd_xjid',$data['inspectId'])
            ->field('node.*,inspect.jd_yz')
            ->select()
            ->toArray();
        } 

            $revs=Db::table('cmf_gz_hise_service_inspection_step')->where('jd_xjid',$data['inspectId'])->find();
            if(!empty($list)){
                foreach($list as $k=>$v){
                   
                $vals=Db::table('cmf_gz_hise_service_inspection_step')->where('jd_xjid',$data['inspectId'])->where('jd_azjd',$v['node_id'])->find();
            
                if($vals){
                    $list[$k]['ts_sfyz']=$vals['ts_sfyz'];
                    if($vals['jd_gfzpone']!=""){
                        $list[$k]['imgInfo'][]=$vals['jd_gfzpone'];    
                      }
                      if($vals['jd_gfzptwo']!=""){
                        $list[$k]['imgInfo'][]=$vals['jd_gfzptwo'];    
                      } 
                      if($vals['jd_gfzpthere']!=""){
                        $list[$k]['imgInfo'][]=$vals['jd_gfzpthere'];    
                      } 
                      if(!isset($list[$k]['imgInfo'])){
                        $list[$k]['imgInfo']=[];  
                      }
                }else{
                    $list[$k]['imgInfo']=[];  
                        
                }
    //验证照片
           $valyz=Db::table('cmf_gz_inspect_step_checking')->where('node',$v['node_id'])->where('tid',$data['inspectId'])->find();
           if($valyz){
            if($valyz['pic_one']!=""){
                $list[$k]['yzInfo'][]=$valyz['pic_one'];    
              }
              if($valyz['pic_two']!=""){
                $list[$k]['yzInfo'][]=$valyz['pic_two'];    
              } 
              if($valyz['pic_three']!=""){
                $list[$k]['yzInfo'][]=$valyz['pic_three'];    
              } 
              if(empty($list[$k]['yzInfo'])){
                $list[$k]['yzInfo']=[];  
              }
           }else{
            $list[$k]['yzInfo']=[];  
           }
                $list[$k]['remark']=$vals['jd_remark'];  
                $list[$k]['yz']=$vals['jd_yz'];
              }
            }
         
       
        // 遍历获取安装单已提交的节点
        foreach ($list as $key => $val) {
            // 获取已提交的节点
            $process = Db::table('cmf_gz_hise_service_pro_process')
                ->alias('p')
                ->join('gz_node n', 'p.azjd = n.node_id')
                ->where('gc_azdid', $data['azd_id'])
                ->where('cplp', $val['type_id'])
                ->field('n.node_id,n.node_name')
                ->order('p.create_time ASC')
                ->select()
                ->toArray();
            // 获取已提交的节点
            $list[$key]['process'] = $process;
        }
        // 获取巡检单ID
        $inspectId = input('post.inspectId');
        // 判断巡检ID是否存在g
        if($inspectId){
            // 获取巡检单编号
            $inspectInfo = Db::table('cmf_gz_hise_service_inspection')
                ->where('xj_azdbh',$data['azd_id'])
                ->where('xj_id',$inspectId)
                ->find();
     
            // 是否存在问题
            $data['xj_sfczwt'] = $inspectInfo['xj_sfczwt'];
            // 巡检结论及工程存在的问题
            $data['xj_xjjlwt'] = $inspectInfo['xj_xjjlwt'];
            // 机型一致性
            $data['xj_jxyzx'] = $inspectInfo['xj_jxyzx'];
            //巡检状态
            $data['xj_yzzt'] = $inspectInfo['xj_yzzt'];
            $data['xj_shzt'] = $inspectInfo['xj_shzt'];
            $data['jd_xjid'] = $inspectInfo['xj_id'];

            $data['inspect_code'] = $inspectInfo['xj_inspectcode'];
            // 获取巡检节点数据
            $nodeList = Db::table('cmf_gz_hise_service_inspection_step')
                ->where('jd_xjid',$inspectId)
                ->order('update_time ASC')
                ->select()
                ->toArray();

            //验证巡检信息
            foreach ($nodeList as $key => $value) {
                $checking = $this->inspectstepchecking($inspectId,$value['jd_azjd']);
                $nodeList[$key]['checking'] = $checking;
            }

            // 巡检节点
            $data['nodeList'] = $nodeList;
        } else {
            // start***************************
            // 保存巡检单信息
            //$inspectId = $this->xunJianAddInfo($data);
            // 判断是否保存成功
            if(empty($inspectId)){
                $this->error('意外的操作，巡检单保存失败');
            }
            // end***************************
        }
     if($list){
        foreach($list as $kll=>$vll){
            if($vll['remark']==null){
                $list[$kll]['remark']="";
            }
        }
     }
        
        // 赋值巡检单ID
        $data['inspectId'] = $inspectId;
        // 赋值节点信息
        $data['list'] = $list;
        //用户类型
        $data['userType']=$this->userType;
        // 返回信息
        $this->success('操作成功！', $data);
    }

//获取验证信息
    public function getyanzheng(){

    }
   //编辑巡检详细信息-----分公司
    /**
     * 安装单巡检添加+编辑-保存
     * @param []
     * @return []
     * @date 2019/12/18 6:42 PM
     */
    public function inspectionAddSubt()
    {
        // 验证的规则
        $rule = [
            'inspectId' => 'require',
            'hise_service_project_id' => 'require',
            'azd_id' => 'require',
            //'fraction' => 'require',
            'is_problem' => 'require',
            'conclusion' => 'require',
            'is_model' => 'require',
        ];
        // 错误的消息
        $msg = [
            'inspectId.require' => '巡检单ID不存在',
            'hise_service_project_id.require' => '安装单主键ID不存在',
            'azd_id.require' => '安装单编号不存在',
            'is_problem.require' => '请选择是否存在问题',
            'conclusion.require' => '请填写结论及工程存在的问题',
            'is_model.require' => '请选择机型是否一致',
        ];
        // 获取的数据
        $inspectid = $this->request->post('inspectId');
        //获取验证照片
        $yzData=$this->request->post('yz');
        // 获取当前类型 1=>新增 2=>编辑
        $type = $this->request->post('type');
        $id = $this->request->post('id');

        $inspectCode = $inspectid;
        $data = [
            'xj_id' => $inspectCode, // 获取巡检单ID
           // 'inspectCode' => $inspectCode, // 获取巡检单编号
            'xj_azdbh' => $this->request->post('hise_service_project_id'), // 安装单主键ID
            'azd_id' => $this->request->post('azd_id'), // 获取安装单编号
            //'fraction' => $this->request->post('fraction'), // 获取评分总数
            'xj_sfczwt' => $this->request->post('is_problem'), // 获取是否存在问题
            'xj_xjjlwt' => $this->request->post('conclusion'), // 获取结论及工程存在的问题
            'xj_jxyzx' => $this->request->post('is_model'), // 获取机型是否一致
            'hise_service_project_id'=>$this->request->post('hise_service_project_id'),
            'inspectId'=>$this->request->post('inspectId')
        ];
        if($type==2&&!$id){
            $this->error('缺少id参数');
        }
        if($type==2&&$id){
            $data['id']=$id;
        }

        // 直接传入验证规则
        $validate = Validate::make($rule)->message($msg);
        // 打分 节点*******************************
        // 获取当前时间
        $time = time();
        // 获取节点数据
        $nodeList = htmlspecialchars_decode(input('post.nodeList'));
        // 格式化json数据  节点照片数据
        $nodeListArray = json_decode($nodeList,true);
        // 判断节点是否为空
        if(empty($nodeListArray)){
            $this->error('请填写节点信息');
        } else {
            // 遍历生成巡检节点数据
            $nodearr = Db::table('cmf_gz_node')->select()->column('node_name','node_id');
            foreach ($nodeListArray as $key=>$val) {
                // 判断是否传参正确
                if(empty($val['type']) && empty($val['node']) && empty($val['is_problem'])){
                    $this->error('意外的操作，节点传参格式错误！');
                }
                // 巡检节点所需参数数据
                $dataStep[$key]['jd_xjid'] = $inspectCode; // 巡检单号
                $dataStep[$key]['jd_cplb'] = $val['type'];  //产品类型
                $dataStep[$key]['jd_azjd'] = $val['node']; // 节点ID
                $dataStep[$key]['jd_gfzpone'] = $val['specs_pic']; // 规范照片1
                $dataStep[$key]['jd_gfzptwo'] = $val['specs_pic_two']; // 规范照片2
                $dataStep[$key]['jd_gfzpthere'] = $val['specs_pic_three']; // 规范照片3
                $dataStep[$key]['jd_nogfzpone'] = $val['no_specs_pic']; // 不规范照片1
                $dataStep[$key]['jdnogfzptwo'] = $val['no_specs_pic_two']; // 不规范照片2
                $dataStep[$key]['jd_nogfzpthere'] = $val['no_specs_pic_three']; // 不规范照片3
                $dataStep[$key]['jd_yz'] = $val['jd_yz']; // 是否需要验证
                $dataStep[$key]['jd_sfczwt'] = $val['is_problem']; // 是否存在问题
            }
        }

        // 启动事务
        Db::startTrans();
        // 获取节点数量
        $countStep = Db::table('cmf_gz_hise_service_inspection_step')->where('jd_xjid', $inspectCode)->count();
        // 判断
        if($type == 1){
            $res=Db::table('cmf_gz_hise_service_inspection_step')->insert($dataStep[0]);
            if($res){
                Db::commit();
                $this->success('操作成功！',['inspectId'=>$data['inspectId']]);
            }
            Db::rollback();
            $this->error('操作失败！',Db::table('cmf_gz_hise_service_inspection_step')->getLastsql());
        } else {
            // 判断是否已添加节点
            if(empty($countStep)){
                // 新增巡检单节点数据
                $result2 = Db::table('cmf_gz_hise_service_inspection_step')->insertAll($dataStep, true);
            } else {
                // 获取巡检节点数据
                $nodeList = Db::table('cmf_gz_hise_service_inspection_step')
                    ->where('id',$id)
                    ->select()
                    ->toArray();
                // 遍历判断是否为修改或者是否为新增
                foreach ($dataStep as $key=>$value) {
                    // 判断巡检节点是否存在
                    $id=true;
                    if($id){
                        // 修改所需参数
                        $mapStepPic['update_time'] = date('Y-m-d H:i:s');
                        $mapStepPic['jd_sfczwt'] = $value['jd_sfczwt'];
                        $mapStepPic['jd_gfzpone'] = $value['jd_gfzpone'];
                        $mapStepPic['jd_gfzptwo'] = $value['jd_gfzptwo'];
                        $mapStepPic['jd_gfzpthere'] = $value['jd_gfzpthere'];
                        $mapStepPic['jd_nogfzpone'] = $value['jd_nogfzpone'];
                        $mapStepPic['jdnogfzptwo'] = $value['jdnogfzptwo'];
                        $mapStepPic['jd_nogfzpthere'] = $value['jd_nogfzpthere'];
                        $mapStepPic['jd_yz'] = $value['jd_yz'];
                        // 已有则进行编辑修改
                        $result2 = Db::table('cmf_gz_hise_service_inspection_step')
                            ->where('id',$id)
                            ->data($mapStepPic)
                            ->update();
                        // 修改失败
                        if(!$result2){
                            // 回滚事务
                            Db::rollback();
                            $this->error('巡检节点保存失败');
                        }
                    } else {
                        // 没有节点则进行新增
                        $result2 = Db::table('cmf_gz_hise_service_inspection_step')->insert($value, true);
                        // 修改失败
                        if(!$result2){
                            // 回滚事务
                            Db::rollback();
                            $this->error('巡检节点保存失败');
                        }
                    }
                }
                // 遍历生成 in 拼接值
                foreach ($dataStep as $key=>$value) {
                    $dataStep[$key]['in'] = $value['jd_xjid'].'.'.$value['jd_cplb'].'.'.$value['jd_azjd'];
                }
                // 键值反转
                $dataStepT = array_column($dataStep,NULL,'in');
                // 定义变量
                $ids = '';
                // 遍历获取无用的节点信息
                foreach ($nodeList as $key=>$val) {
                    $in = $val['jd_xjid'].'.'.$val['jd_cplb'].'.'.$val['jd_azjd'];
                    if(!array_key_exists($in,$dataStepT)){
                        $ids[] = $val['jd_xjid'];
                    }
                }
                // 判断是否有无用的节点
                if($ids){
                    // 删除无用的节点信息
                    $result4 = Db::table('cmf_gz_hise_service_inspection_step')->where('id','in',$ids)->delete();
                    // 修改失败
                    if(!$result4) {
                        // 回滚事务
                        Db::rollback();
                        $this->error('巡检节点保存失败');
                    }
                  }
            }
        }
        // 打分 节点 end*************************
        // 巡检单所需参数数据
        $mapIns['xj_gcjd'] = Db::table('cmf_gz_hise_service_project')->where('hise_service_project_id',$data['hise_service_project_id'])->value('gczt'); // 工程进度
        $mapIns['xj_sfczwt'] = $data['xj_sfczwt']; // 是否存在问题 0:否,1:是
        $mapIns['xj_xjjlwt'] = $data['xj_xjjlwt']; // 巡检结论及工程存在的问题  
        $mapIns['xj_jxyzx'] = $data['xj_jxyzx']; // 机型一致性 0:不一致,1:一致
        //$mapIns['fraction'] = $data['fraction']; // 评分总数
        $mapIns['update_time'] = date('Y-m-d H:i:s'); // 更新时间
        $mapIns['xj_xjr'] = isset($this->user['mobilphone']) ? $this->user['mobilphone'] : ''; // 巡检人
        // 修改巡检信息
        $result3 = Db::table('cmf_gz_hise_service_inspection')
            ->where('xj_azdbh',$data['azd_id'])
            ->data($mapIns)
            ->update();
        // 判断是否添加成功
        if($result3 && $result2){
            // 提交事务
            Db::commit();
            // 返回信息
            $this->success('操作成功！',['inspectId'=>$data['inspectId']]);
        } else {
            // 回滚事务
            Db::rollback();
            $this->error('操作失败！');
        }
    }
    //保存巡检
    public function inspectSave()
    {
      $img=input('post.');
      $imgRemarkRes="";
      //$len=count($img);
      foreach($img['img'] as $k=>$v){
        Log::info('开始组装数据');
        $data['update_time']=date('Y-m-d H:i:s',time());   
        $data['jd_xjid']=$img['inspect_code'];
        $data['jd_cplb']=$img['type'];
        $data['jd_azjd']=$v['node_id'];
        $data['jd_gfzpone']="";
        $data['jd_gfzptwo']="";
        $data['jd_gfzpthere']="";
        $node_name=Db::table('cmf_gz_node')->where('node_id',$v['node_id'])->value('node_name');
      if(Db::table('cmf_gz_node')->where('node_id',$v['node_id'])->find()){
           Log::info($img['node'].'节点数据拼接');
           $data['jd_jdname']=Db::table('cmf_gz_node')->where('node_id',$v['node_id'])->value('node_name');
        }

        // dump($v['img'][0]['url']);
        //照片拼接

       if(isset($v['img'][0]['url'])){
           $data['jd_gfzpone']=$v['img'][0]['url'];
       }
       if(isset($v['img'][1]['url'])){
        $data['jd_gfzptwo']=$v['img'][1]['url'];
       }
       if(isset($v['img'][2]['url'])){
        $data['jd_gfzpthere']=$v['img'][2]['url'];
       }
        $data['jd_remark']=$v['remark'];
        $imgRemarkRes=true;
          if(!$v['remark'] and count($v['img'])<1){
            if($v['yz']=='1'){
                $this->error('上传照片后填写说明',[]);
            }
          }
        if($v['yz']=='1'){
         if(!$v['remark']){
               $this->error('上传照片后填写说明',[]);
	   }
	}
        $data['jd_yz']=$v['yz'];
        $resisup=Db::table('cmf_gz_hise_service_inspection_step')->where('jd_xjid',$img['inspect_code'])->where('jd_azjd',$v['node_id'])->find();
     
        if($resisup){
               
                 //更改
                 $res=Db::table('cmf_gz_hise_service_inspection_step')->where('jd_xjid',$img['inspect_code'])->where('jd_azjd',$v['node_id'])->update($data);  

                //  if(!$res){
                //     Log::info('更改巡检失败');
                //  }
              }else{
                  //保存
                  $res=Db::table('cmf_gz_hise_service_inspection_step')->insert($data);
                  if(!$res){
                    Log::info('保存巡检失败');
            }
         }
    }
       // $imgRemarkRes = explode('1',$imgRemarkRes);
       // $imgRemarkRes=count($imgRemarkRes);

        // if(!$imgRemarkRes){
        //     $this->error('上传照片后填写说明',[]);
        // }

    $this->success('操作成功',[]);
 
    }
    //编辑巡检详情
    public function inspectEdit(){
        $yz=input('post.');
        $img=input('post.img/a');
        $res=Db::table('cmf_gz_hise_service_inspection_step')->setField([
            'jd_xjid'=>$yz['inspect_code'],//巡检单号
            'jd_cplb'=>$yz['type'],//节点类别
            'jd_azjd'=>$yz['node'],//节点id
            'jd_gfzpone'=>$img[0],//图片1
            'jd_gfzptwo'=>$img[1],//图片2
            'jd_gfzpthere'=>$img[2],//图片3
            'jd_sfczwt'=>$yz['jd_sfczwt'],
            'jd_yz'=>$yz['jd_yz'],  //是否需要验证
            'update_time'=>date('Y-m-d H:i:s',time())
        ]);
        if($res){
            $this->success('操作成功',[]);
        }
        $this->error('操作失败',[]);
    }
   //查看单节点照片
    public function inspectInfos(){
        $inspect_code=input('post.inspect_code');//巡检单号
        $node_id=input('post.node_id');//节点id
        $res['xjinfo']=Db::table('cmf_gz_hise_service_inspection')->where('xj_id', $inspect_code)->find();
        $res['xjpc']=Db::table('cmf_gz_hise_service_inspection_step')->where('jd_xjid',$inspect_code)->where('jd_azjd',$node_id)->find();
  
        $res['yzpc']=Db::table('cmf_gz_inspect_step_checking')->where('tid',$inspect_code)->where('node',$node_id)->find();
        if($res['xjpc']!==null){

                if($res['xjpc']['jd_gfzpone']){
                    $res['xjpc']['jd_gfzpone']=[$res['xjpc']['jd_gfzpone']];
                }
               if($res['xjpc']['jd_gfzptwo']){
                array_push($res['xjpc']['jd_gfzpone'],$res['xjpc']['jd_gfzptwo']);
                unset($res['xjpc']['jd_gfzptwo']);
               }
               if($res['xjpc']['jd_nogfzpthere']){
                array_push($res['xjpc']['jd_gfzpone'],$res['xjpc']['jd_gfzpthere']);
                unset($res['xjpc']['jd_gfzpthere']);
               }
        }
     if($res['yzpc']!==null){
            if($res['yzpc']['pic_one']){
                $res['yzpc']['pic_one']=[$res['yzpc']['pic_one']];
            }
           if($res['yzpc']['pic_two']){
            array_push($res['yzpc']['pic_one'],$res['yzpc']['pic_two']);
            unset($res['yzpc']['pic_two']);
           }
           if($res['yzpc']['pic_three']){
            array_push($res['yzpc']['pic_one'],$res['yzpc']['three']);
            unset($res['yzpc']['three']);
           }
           if($res['yzpc']['pic_four']){
            array_push($res['yzpc']['pic_one'],$res['yzpc']['pic_four']);
            unset($res['yzpc']['pic_four']);
           }
           if($res['yzpc']['pic_five']){
            array_push($res['yzpc']['pic_one'],$res['yzpc']['pic_five']);
            unset($res['yzpc']['pic_five']);

           }

     }
        if($res['yzpc']==null){
            $res['yzpc']=[
                'id'=>'',
                'uid'=>'',
                'tid'=>'',
                'type'=>'',
                'type_bm'=>'',
                'node'=>'',
                'inspect_code'=>'',
                'node_name'=>'',
                'pic_one'=>[],
                'create_time'=>'',
                'update_time'=>''
            ];
        }
        if($res['xjpc']==null){
            $res['xjpc']=[
                'jd_xjid'=>'',
                'jd_cplb'=>'',
                'jd_azjd'=>'',
                'jd_gfzpone'=>[],
                'jd_nogfzpone'=>'',
                'jdnogfzptwo'=>'',
                'jd_nogfzpthere'=>'',
                'jd_sfczwt'=>'',
                'jd_remark'=>'',
                'jd_yz'=>'',
                'ts_sfyz'=>'',
                'update_time'=>''
            ];
        }
       
       
        if($res){
            $this->success('操作成功',$res);
        }
            $this->success('操作成功',['jd_gfzpone'=>'']);
    }
    //提交巡检
    public function inspectSubmit()
    {
     $xj_id=input('post.xj_id');
     $zl=input('post.zl');
   //dump($_POST);
     $res=Db::table('cmf_gz_hise_service_inspection_step')->where('jd_xjid',$xj_id)->find();
     if(!$res){
          $this->error('至少保存一个节点数据',[]);
     }
//dump($zl);die;
    if($zl==1){
       //如果战略 每个节点必须编辑
        $zlnodedata=Db::table('cmf_gz_node')->where('type',3)->select();
       //  dump($zlnodedata);die;
        foreach($zlnodedata as $kzlnode=>$vzlnode){
              $is_have=Db::table('cmf_gz_hise_service_inspection_step')->where('jd_xjid',$xj_id)->where('jd_azjd',$vzlnode['node_id'])->value('jd_gfzpone');
            		//dump($is_have);
		   if(!$is_have){
 			$this->error('节点需要全部巡检');
		}
	   }
	}
   //die;
     if(Db::table('cmf_gz_hise_service_inspection_step')->where('jd_xjid',$xj_id)->where('jd_yz',1)->find()){ 
        //需要验证
          Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$xj_id)->update([
            'update_time'=>date('Y-m-d H:i:s',time()),
            'xj_xjzt'=>2
       ]);
     }else{
         //没有问题需要验证
         Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$xj_id)->update([
            'update_time'=>date('Y-m-d H:i:s',time()),
            'xj_xjzt'=>2
       ]);
     }
     $this->success('操作成功',[]);
    }
     //提交验证--服务商
     public function inspectSubmityz(){
         $xj_id=input('xj_id');
        $xj_xjzt= Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$xj_id)->value('xj_xjzt');

       $yzres=Db::table('cmf_gz_hise_service_inspection_step')->where('jd_xjid',$xj_id)->where('jd_yz',1)->select();

       if(!empty($yzres)){
        $yzres=$yzres->toArray();
        foreach($yzres as $k=>$v){
            $rescheck=Db::table('cmf_gz_inspect_step_checking')->where('tid',$v['jd_xjid'])->where('node',$v['jd_azjd'])->find();
            if(!$rescheck){
                $this->error('节点验证未完成');
            }
        }
       }
   
       $res=Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$xj_id)->find();

     if(isset($rescheck)){
        //验证提交成功
        //$rescheck=Db::table('cmf_gz_inspect_step_checking')->where('tid',$v['jd_xjid'])->where('node',$v['jd_azjd'])->find();
        Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$xj_id)->update([
            'xj_xjzt'=>4
        ]);
        $this->success('验证完成',[]);      
     }

     if($res['xj_is_wp']=='0'){
        Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$xj_id)->update([
            'xj_xjzt'=>5,
            'xj_shzt'=>1
        ]);
        $this->success('验证完成',[]); 
     }
      $this->error('当前节点未验证完成',[]);  
     }

    //分公司提交验证--合格
    public function inspectTest()
    {

        $xj_id=input('post.xj_id');
        $status=input('post.status');


        $yzres=Db::table('cmf_gz_hise_service_inspection_step')->where('jd_yz',1)->where('jd_xjid',$xj_id)->select();
        if(!empty($yzres)){
            $yzres->toArray();
            foreach($yzres as $kyz=>$vyz){
                $checkres=Db::table('cmf_gz_inspect_step_checking')->where('tid',$vyz['jd_xjid'])->find();
                if(empty($checkres)){
                    $this->error('存在未验证节点');
                }
              
                    if($checkres['pic_one']=="" and $checkres['pic_two']=="" and $checkres['pic_three']==""){
                        $this->error('存在未验证节点');
                    }
            }
        }




        $xj_xjzt=Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$xj_id)->value('xj_xjzt');
        if($xj_xjzt<2){
            $this->error('操作失败');
        }
        $data['xj_xjzt']=5;
        if($status=='1'){
           $data['xj_shzt']=1;
        }else{
            $data['xj_shzt']=2;
        }
        $res=Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$xj_id)->update($data);
        if($res){
            $this->success('操作完成',[]);
        }
        $this->error('请勿重复操作',[]);
    }

    //保存验证
    public function inspectTestSave()
    {
         
    }

    //删除巡检
    public function inspectDel()
    {
      $xj_id=$this->request->post('xj_id');
      $azd_id=$this->request->post('azd_id');
      $res=Db::table('cmf_gz_hise_service_inspection')->where(['xj_id'=>$xj_id])->delete();
      //查询是否还存在安装单
      $jxRes=Db::table('cmf_gz_hise_service_inspection')->where('xj_azdbh',$azd_id)->select();
      if(empty($jxRes)){
          Db::table('cmf_gz_hise_service_project')->where('azd_id',$azd_id)->setField(['inspection'=>0]);
      }
      if($res){
          $this->success('删除成功',[]);
      }
        $this->error('删除失败',[]);
    }

    //派工巡检
    public function inspectAssign()
    {
       //查询出服务商
    }

    //分公司服务工程师验证服务商巡检是否合格，驳回，合格
    public function inspectChecking()
    {

    }

    //接收巡检单  --服务商
    public function inspectReceive()
    {
     $xj_id=input('post.xj_id');
     $userData=$this->user;
     $res=Db::table('cmf_gz_hise_service_inspection')->where(['xj_id'=>$xj_id])->setField(['xj_xjr'=>$userData['phone'],'xj_xjzt'=>1]);
     if($res){
         $this->success('操作成功',[]);
     }
     $this->error('操作失败',[]);
    }
    //驳回巡检单---服务商
    public function inspectReject(){
        $xj_id=input('post.xj_id');
        $userData=$this->user;
        $res=Db::table('cmf_gz_hise_service_inspection')->where(['xj_id'=>$xj_id])->setField(['xj_xjr'=>$userData['mobilphone'],'xj_xjzt'=>'X']);
        if($res){
            $this->success('操作成功',[]);
        }
        $this->error('操作失败',[]);
    }
    //按条件查询 巡检单
    public function search(){
        $data=input('get.');
        $where=[];
        foreach($data as $k=>$v){
            $where[][$k]=$v;
        }
        $data=Db::table('cmf_gz_hise_service_inspection')->where($where)->paginate(10);
        if($data){
           $this->success('操作成功',$data);
        }
        $this->error('操作失败',[]);
    }
    //保存验证状态
    public function saveInspectstus(){
        $xj_id=input('post.xj_id');
        $status=input('post.status');
        $res=Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$xj_id)->update(['xj_shzt'=>$status]);
       if($res){
        $this->success('操作成功',[]);
       }
       $this->error('操作失败',[]);
    }
    /**
     * 获取随机编码
     * @param []
     * @return []
     * @date 2019/12/19 10:10 AM
     */
    public function nonceStr() {
        static $seed = array(0,1,2,3,4,5,6,7,8,9);
        $str = '';
        for($i=0;$i<8;$i++) {
            $rand = mt_rand(0,count($seed)-1);
            $temp = $seed[$rand];
            $str .= $temp;
            unset($seed[$rand]);
            $seed = array_values($seed);
        }
        $time = date('Ymd',time());
        return $time.$str;
    }

    /**
     * 获取巡检验证数据
     * @param []
     * @return []
     * @date 2019/12/19 10:10 AM
     */
    public function inspectstepchecking($inspectId,$node) {
        $countScor = Db::table('cmf_gz_inspect_step_checking')->where('node', $node)->where('tid', $inspectId)->find();
        if($countScor)
        {
            return $countScor;
        }
        return [];
    }
    /**
     * 巡检信息新增
     * @param []
     * @return []
     * @date 2019/12/20 11:55 AM
     */
    protected function xunJianAddInfo($data)
    {
        // 获取巡检单编号
        $inspectId = Db::name('cmf_gz_hise_service_inspection')
            ->where('xj_azdbh',$data['azd_id'])
            ->where('xj_xjr',$this->userId)
            ->where('xj_id',$data['inspect_code'])
            ->value('xj_id');
        // 判断是否已存在该巡检单
        if(empty($inspectId)){
            // 巡检单参数
            $map['xj_id'] = $data['hise_service_project_id']; // 安装单ID
            $map['uid'] = $this->userId; // 用户ID
            $map['azd_id'] = $data['azd_id']; // 安装单编号
            $map['inspect_status'] = 1; // 巡检状态 1:初始,2:提交
            $map['progress'] = Db::name('rl_hise_service_project')->where('hise_service_project_id', $data['hise_service_project_id'])->value('gczt'); // 工程进度
            $map['vrct_status'] = 1; // 验证状态 1:未验证,2:已验证
            $time = time(); // 获取当前时间
            $map['inspect_time'] = $time; // 巡检时间
            $map['create_time'] = $time; // 创建时间
            $map['update_time'] = $time; // 更新时间
            $map['u_name'] = isset($this->user['user_name']) ? $this->user['user_name'] : '';
            $map['inspect_code'] = $data['inspect_code']; // 巡检编码
            $map['uPhone'] = Db::table('cmf_rl_zsms_user_query')->where('zsms_user_query_id',$this->userId)->value('user_id'); // 巡检人手机号******
            // 添加巡检单数据
            $inspectId = Db::name('rl_inspect')->insertGetId($map);
            // 返回巡检ID
            return $inspectId;
        } else {
            return $inspectId;
        }
    }
    /**
     * 上传巡检单节点图片
     * @param []
     * @return []
     * @date 2019/12/21 12:06 PM
     */
    public function inspectionUploadPic()
    {
        // 获取上传文件
        $file = $this->request->file('image');
        $place = $this->request->param('place','是空的，没有值');
        // 判断图片是否存在
        if (empty($file)) {
            $this->error('请选择上传文件');
        }
        // 获取当前时间
        $date = date('Ymd',time());
        // 移动到框架应用根目录/uploads/ 目录下 3MB
        $info = $file->rule('md5')->move( '../uploads/inspect/'.$date);
        // 判断图片是否上传成功
        if($info){
            // 成功上传后 获取上传信息
            $orpath = ROOT_PATH.'public/uploads/inspect/'.$date.'/'.$info->getSaveName();
            $logo = ROOT_PATH.'logo.png';
            // 旋转图像
            $logo_rotate = \think\Image::open($logo)->rotate(-45)->save(ROOT_PATH.'public/uploads/logo_45.png');
            $logo_45 = ROOT_PATH.'public/uploads/logo_45.png';
            // 添加水印
            $this->water_all($orpath ,$logo_45, $orpath, 15);
            $image = \think\Image::open($orpath);
            $image->text($place."\n".date('Y-m-d H:i:s'),ROOT_PATH.'msyh.ttc',14,'#FF0000',9,0,0)->save($orpath);
            $list['path'] = 'http://'.$_SERVER['SERVER_NAME'] .'/uploads/inspect/'.$date.'/'.$info->getSaveName();
            $this->success('操作成功！', $list);
        }else{
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }
    /**
     * 添加全屏水印
     * @param  [type] $origin [原图]
     * @param [type] $[logo] [水印图片]
     * @param [type] $[pathname] [保存路径]
     * @param [type] $[opacity] [透明度]
     * @return [type]         [description]
     */
    public function water_all($origin,$logo,$pathname,$opacity = 20)
    {
        $im = imagecreatefromstring(file_get_contents($origin));
        //获取水印源
        $watermark = imagecreatefromstring(file_get_contents($logo));
        //获取图、水印 宽高类型
        list($bgWidth, $bgHight, $bgType) = getimagesize($origin);
        list($logoWidth, $logoHight, $logoType) = getimagesize($logo);
        //定义平铺数据
        $x_length = $bgWidth - 10; //x轴总长度
        $y_length = $bgHight - 10; //y轴总长度
        //创建透明画布 伪白色
        $w = imagesx($watermark);
        $h = imagesy($watermark);
        $cut = imagecreatetruecolor($w,$h);
        $white = imagecolorallocatealpha($cut, 255,255,255,0);
        imagefill( $cut, 0, 0, $white );
        //整合水印
        imagecopy($cut, $watermark, 0, 0, 0, 0, $w, $h);
        //循环平铺水印
        for ($x = 0; $x < $x_length; $x++)
        {
            for ($y = 0; $y < $y_length; $y++) {
                imagecopymerge($im, $cut, $x, $y, 0, 0, $logoWidth, $logoHight, $opacity);
                $y += $logoHight;
            }
            $x += $logoWidth;
        }
        //header("Content-type:image/png");
        // imagejpeg 的第二个参数不传, 默认是显示图片
        imagejpeg($im,$pathname);
        empty($im) || imagedestroy($im);
    }
   /*保存验证信息*/
    public function saveInspectionCheck(){
        $yz=input('post.');
        // Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$yz['tid'])->setField([
        //     "xj_xjzt"=>3
        //  ]);
      if(empty($yz['list'])){
        $this->success('操作成功');
        }
        foreach($yz['list'] as $k=>$v){
  
                 $data['node']=$v['node_id'];//节点id
                 $data['inspect_code']=$yz['tid'];//巡检单号
                 $data['tid']=$yz['tid'];//巡检单id
                 $data['pic_one']="";
                 $data['pic_two']="";
                 $data['pic_three']="";
                 $userData=$this->user;
                 $Checkinfo=Db::table('cmf_gz_hise_service_inspection')->where('xj_id',$data['tid'])->find();
                 if($Checkinfo['xj_is_wp']=='1'){
                     $data['uid']=$userData['et_azd_id'];  //用户idgi
                }else{
                     $data['uid']=$userData['zsms_user_query_id'];  //用户idgi
                }
                $data['type']=$v['type_id']; //节点类型
                $data['type_bm']=$v['type_id'];//类别编码
                $data['node_name']=$v['node_name'];//类别名称
                if(isset($v['yzimg'][0]['url'])){
                    $data['pic_one']=$v['yzimg'][0]['url'];//照片1
                }
                if(isset($v['yzimg'][1]['url'])){
                    $data['pic_two']=$v['yzimg'][1]['url'];//照片1
                }
                if(isset($v['yzimg'][2]['url'])){
                    $data['pic_three']=$v['yzimg'][2]['url'];//照片1
                }

                if($v['yz']==1){
                    if(count($v['yzimg'])<1){
                         $this->error('请上传验证照片');
                      }
                    }




                $data['create_time']=time();//创建时间
                 $data['update_time']=time();//创建时间

                 $whereres['inspect_code']= $data['tid'];
                 $whereres['node']= $v['node_id'];
                 $rell=Db::table('cmf_gz_inspect_step_checking')->where($whereres)->find();
                 if($rell){
                    $res=Db::table('cmf_gz_inspect_step_checking')->where($whereres)->update($data);
                 }else{
                     $res=Db::table('cmf_gz_inspect_step_checking')->insert($data);
                 }
                 $where['jd_xjid']=$data['tid'];
                 $where['jd_azjd']=$v['node_id'];
                 $jd_remark=$v['remark'];
                 $updateData=[];

                 if(isset($jd_remark)){
                      $updateData['jd_remark']=$jd_remark;
                 }
            if(isset($v['ts_sfyz'])){
                $updateData['ts_sfyz'] = $v['ts_sfyz'];
            }

                 Db::table('cmf_gz_hise_service_inspection_step')->where($where)->setField($updateData);
                 
        }

	
        $this->success('操作成功',$res);
    }
    /*查询单个节点验证照片*/
    public function findInspectCheck(){
        $where['node']=input('post.node_id');//节点id
        $where['inspect_code']=input('post.inspect_code');//巡检单号
        $res=Db::table('cmf_gz_inspect_step_checking')->where($where)->find();
        $wheres['jd_xjid']=$data['inspect_code'];
        $res['jd_yz']=Db::table('cmf_gz_hise_service_inspection_step')->where($wheres)->value('jd_yz');
        $res['jd_remark']=Db::table('cmf_gz_hise_service_inspection_step')->where($wheres)->value('jd_remark');
        if($res){
            $this->success($res);
        }
        $this->error($res);
    }
    //缺少
    // 删除照片
    public function delPto(){
        $pto=input('post.img');

        $path=$_SERVER['DOCUMENT_ROOT'].$this->imngSrc($pto);
        if(file_exists($path)){
            unlink($path);
            $this->success('删除成功');
         }
         $this->error('图片不存在');     
    }
    public function imngSrc($str){
       // preg_match_all('/https?:\/\/[\w-.%',$str,$mat);
        $mat=parse_url($str);
        return $mat['path'];
    }
}
